package com.xhsj.user.pms.oareply.web;

import com.alibaba.fastjson.JSONObject;
import com.xhsj.user.generalprocess.mapper.TbPamGeneralNodeMapper;
import com.xhsj.user.generalprocess.vo.GeneralAuditHistoryVo;
import com.xhsj.user.pms.oareply.dto.FindRunTaskDto;
import com.xhsj.user.pms.oareply.vo.PatentOaAuditVo;
import com.xhsj.user.pms.oareply.vo.PatentOaHiTaskVo;
import com.xhsj.user.pms.oareply.vo.PatentOaRunTaskVo;
import com.xhsj.user.pms.patent.vo.ProcessNodeVo;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.ApiOperation;
import com.baomidou.mybatisplus.core.metadata.IPage;

import java.util.*;
import java.util.stream.Collectors;

import com.xhsj.user.utils.Message;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;

import org.springframework.web.bind.annotation.RestController;


import com.xhsj.user.pms.oareply.service.TbPamPatentOaService;
import com.xhsj.user.pms.oareply.entity.TbPamPatentOa;

import javax.validation.Valid;


/**
 * <p>
 * 专利OA答复 前端控制器
 * </p>
 *
 * @author liuqinghua
 * @since Jul 28, 2021 8:04:28 AM
 */
@Slf4j
@Api(tags = "专利OA答复")
@RestController
@RequestMapping("/oareply/tbPamPatentOa")
public class TbPamPatentOaController {

	@Autowired
    public TbPamPatentOaService service;

	@Autowired
	private TbPamGeneralNodeMapper tbPamGeneralNodeMapper;


	/**
	 * 保存/修改
	 * @author liuqinghua
	 * @date Jul 28, 2021 8:04:28 AM
	 */
	@ApiOperation(value = "专利OA答复,保存/修改", notes = "专利OA答复,保存和修改方法")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
    // @PreAuthorize("hasAuthority('tb:pam:patent:oa:edit')")
	public Message save(@RequestBody @Valid TbPamPatentOa data, BindingResult bindingResult){

		if (bindingResult.hasErrors()) {
			log.info(bindingResult.getFieldError().getDefaultMessage());
			return Message.error(1,bindingResult.getFieldError().getDefaultMessage());
		}

    	try {
    		service.startProcess(data);
			return Message.success("成功");
		} catch (Exception e) {
			log.error("保存失败:{}",e);
        	return Message.error(1,"失败");
		}
	}

	/**
	 * 查询正在执行中任务
	 * @author 苏小林
	 * @date 2021/7/30 16:07
	 * @param: baseParam
	 * @return: com.xhsj.user.utils.Message
	 */
	@RequestMapping(value = "/findRunTask", method = RequestMethod.POST)
	public Message findRunTask(@RequestBody FindRunTaskDto baseParam) {

		try {
			IPage<PatentOaRunTaskVo> selectPage = service.findRunTask(baseParam);
			return Message.success("成功", selectPage.getRecords(), selectPage.getTotal(), selectPage.getPages());
		} catch (Exception e) {
			log.error("失败:{}", e);
			return Message.error(1, e.getMessage());
		}
	}

	/**
	 * 查询历史任务
	 * @author 苏小林
	 * @date 2021/7/30 16:07
	 * @param: baseParam
	 * @return: com.xhsj.user.utils.Message
	 */
	@RequestMapping(value = "/findHiTask", method = RequestMethod.POST)
	public Message findHiTask(@RequestBody FindRunTaskDto baseParam) {

		try {
			IPage<PatentOaHiTaskVo> selectPage = service.findHiTask(baseParam);
			return Message.success("成功", selectPage.getRecords(), selectPage.getTotal(), selectPage.getPages());
		} catch (Exception e) {
			log.error("失败:{}", e);
			return Message.error(1, e.getMessage());
		}
	}


	/**
	 * 处理流程2-处理人上传 意见陈述书
	 *
	 * @author 苏小林
	 * @date 2021/3/9 16:17
	 * @return: com.xhsj.user.utils.Message
	 */
	@RequestMapping(value = "/handleProcessNode", method = RequestMethod.POST)
	public Message handleProcessNode(@RequestBody @Valid PatentOaAuditVo patentOaAuditVo, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			for (ObjectError allError : bindingResult.getAllErrors()) {
				log.error("参数校验:{}", allError.getDefaultMessage());
				return Message.error(1, allError.getDefaultMessage());
			}
		}

		try {
			service.handleProcessNode(patentOaAuditVo);
			return Message.success("成功");
		} catch (Exception e) {
			log.error("失败:{}", e);
			return Message.error(1, e.getMessage());
		}
	}


	/**
	 * 查询流程进度接口
	 * @author 苏小林
	 * @date 2021/8/2 15:20
	 * @param: dataId
	 * @return: com.xhsj.user.utils.Message
	 */
	@RequestMapping(value = "/getProgress", method = RequestMethod.GET)
	public Message getProgress(@RequestParam("dataId") Long dataId) {
		try {
			JSONObject jsonObject = new JSONObject();
			TbPamPatentOa byId = service.getById(dataId);
			int execOrder = byId.getNodeId().intValue();
			List<ProcessNodeVo> list = tbPamGeneralNodeMapper.getNodeListByProcessType("patent_oa");
			ProcessNodeVo vo = new ProcessNodeVo();
			vo.setNodeId(8);
			vo.setNodeName("完结");
			list.add(vo);
			if (!"完结".equals(byId.getNodeName())) {
				ProcessNodeVo processNodeVo1 = list.stream().filter(processNodeVo -> processNodeVo.getNodeId() == byId.getNodeId()).findAny().get();
				execOrder = processNodeVo1.getExecOrder();
			}
			jsonObject.put("nodeList", list);
			jsonObject.put("cutNodeId", execOrder);

			return Message.success("成功", jsonObject);
		} catch (Exception e) {
			log.error("失败:{}", e);
			return Message.error(1, e.getMessage());
		}

	}

	/**
	 * 查询审核历史
	 * @author 苏小林
	 * @date 2021/8/2 15:48
	 * @param: dataId
	 * @param: page
	 * @param: size
	 * @return: com.xhsj.user.utils.Message
	 */
	@RequestMapping(value = "/getAuditHistory", method = RequestMethod.GET)
	public Message getAuditHistory(@RequestParam("dataId") Long dataId,
								   @RequestParam(value = "page", defaultValue = "1") int page,
								   @RequestParam(value = "size", defaultValue = "20") int size) {

		try {
			IPage<GeneralAuditHistoryVo> selectPage = service.getAuditHistory(dataId, page, size);
			return Message.success("成功", selectPage.getRecords(), selectPage.getTotal(), selectPage.getPages());
		} catch (Exception e) {
			log.error("失败:{}", e);
			return Message.error(1, e.getMessage());
		}

	}

	/**
	 * 通过id删除数据
	 * @author liuqinghua
	 * @date Jul 28, 2021 8:04:28 AM
	 */
	@ApiOperation(value = "专利OA答复删除", notes = "通过id删除专利OA答复信息。")
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
    // @PreAuthorize("hasAuthority('tb:pam:patent:oa:delete')")
	public Message delete(@RequestParam(value="id") Long id) {
		try {
			service.removeById(id);
        	return Message.success("成功");
		} catch (Exception e) {
			log.error("删除失败:{}",e);
            return Message.error(1,"失败");
		}
	}


    /**
    * 分页查询数据
    * @author liuqinghua
    * @date Jul 28, 2021 8:04:28 AM
    */
	@ApiOperation(value = "分页查询专利OA答复list", notes = "带参数查询,{\"page\": 1,\"size\": 5,......}。支持模糊查询")
	@RequestMapping(value="/findList",method = RequestMethod.POST)
    // @PreAuthorize("hasAuthority('tb:pam:patent:oa:view')")
	public Message findList(@RequestBody Map<String,Object> data) {
        try {
        	IPage<TbPamPatentOa> selectPage = service.selectPage(data);
    		return Message.success("成功",selectPage.getRecords(),selectPage.getTotal(),selectPage.getPages());
        } catch (Exception e) {
			log.error("查询异常:{}",e);
    		return Message.error(1,"失败");
        }
	}

    /**
    * 查询所有数据
    * @author liuqinghua
    * @date Jul 28, 2021 8:04:28 AM
    */
	@ApiOperation(value = "查询专利OA答复所有数据list", notes = "查询专利OA答复所有数据list。")
	@RequestMapping(value="/findAll",method = RequestMethod.POST)
    // @PreAuthorize("hasAuthority('tb:pam:patent:oa:view')")
	public Message findAll(){
        return Message.success("成功",service.selectAll());
	}

    /**
    * 通过id获取实体类
    * @author liuqinghua
    * @date Jul 28, 2021 8:04:28 AM
    */
	@ApiOperation(value = "通过id获取专利OA答复实体类", notes = "通过id获取专利OA答复实体类。")
	@RequestMapping(value="/getById",method = RequestMethod.GET)
	public Message getById(@RequestParam(value="id") Long id) {
    	return Message.success("成功",service.getById(id));
	}

}

